package com.atguigu.gmall.common.config.interceptor;

import com.atguigu.gmall.common.constant.RedisConstant;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.common.util.RequestUtil;
import com.atguigu.gmall.model.cart.entity.UserAuth;
import com.atguigu.gmall.model.user.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class UserAuthContext {

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    public UserAuth getUserAuth() {
        UserAuth userAuth = new UserAuth();
        HttpServletRequest request = RequestUtil.getRequestForThread();
        //获取cookie中的东西
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("token".equalsIgnoreCase(name)) {
                    UserInfo userInfo = getUserInfo(cookie.getValue());
                    if (userInfo != null) {
                        userAuth.setUserId(userInfo.getId());
                    }
                }
                if ("userTempId".equalsIgnoreCase(name)) {
                    userAuth.setUserTempId(cookie.getValue());
                }
            }
        }
        //2、cookie中没有这样的数据,看请求头有没有
        if (userAuth.getUserId() == null || !StringUtils.hasText(userAuth.getUserTempId())) {
            String token = request.getHeader("token");
            if (StringUtils.hasText(token)) {
                UserInfo userInfo = getUserInfo(token);
                if (userInfo != null) {
                    userAuth.setUserId(userInfo.getId());
                }
            }
            String userTempId = request.getHeader("userTempId");
            if (StringUtils.hasText(userTempId)) {
                userAuth.setUserTempId(userTempId);
            }
        }
        return userAuth;
    }


    private UserInfo getUserInfo(String token) {
        if (token == null) {
            return null;
        }
        //从reids拿到userInfo
        String jsonStr = stringRedisTemplate.opsForValue()
                .get(RedisConstant.REDIS_USER_INFO_PREFIX + token);
        //json转换成UserInfo
        if (!StringUtils.hasText(jsonStr)) {
            return null;
        }
        UserInfo userInfo = JSONs.stringToObj(jsonStr, UserInfo.class);
        return userInfo;
    }
}
